package org.mao.parser;

import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mao.forum.dao.ForumPostDao;
import org.mao.forum.dao.ForumPostImageDao;
import org.mao.forum.entity.ForumPost;
import org.mao.forum.entity.ForumPostImage;
import org.mao.forum.vo.ForumTaskParamsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service("LwgodForumPageParser")
public class LwgodForumPageParser extends BaseForumParser implements IForumPageParser {

	private static Logger logger = Logger.getLogger(LwgodForumPageParser.class);

	@Autowired
	private ForumPostDao forumPostDao;

	@Autowired
	private ForumPostImageDao forumPostImageDao;

	// 根据一个板块，列出要读的每页的url
	@Override
	public List<String> readSectionList(Integer sectionId, ForumTaskParamsVo paramsVo) {
		return super.readSectionList(sectionId, paramsVo);
	}

	// 读某板块的一页上所有的帖子url
	@Override
	public List<ForumPost> readSisPostList(String sectionUrl, Integer sectionId) {
		List<ForumPost> postList = Lists.newArrayList();
		try {
			Document doc = Jsoup.connect(sectionUrl).timeout(5000).get();
			Elements tables = doc.select("#threadlisttableid");
			if (CollectionUtils.isNotEmpty(tables)) {
				Element table = tables.get(0);
				Elements tbodys = table.select("tbody");
				if (CollectionUtils.isNotEmpty(tbodys)) {
					for (Element tbody : tbodys) {
						Elements ths = tbody.select("th");
						if (CollectionUtils.isNotEmpty(ths)) {
							Element th = ths.get(0);
							Elements links = th.select(">a");
							if (CollectionUtils.isNotEmpty(links)) {
								String postNumber = null;
								String postName = null;
								String url = null;
								for (Element link : links) {
									String href = link.attr("abs:href");
									if (link.hasAttr("id")) {
										postNumber = link.attr("id");
									}
									if (href != null && href.endsWith("html")) {
										postName = link.text();
										url = href;
									}
								}
								ForumPost forumPost = super.initForumPost(postNumber, postName, sectionId, url);
								if (forumPost.getId() == null) {
									postList.add(forumPost);
								}
							}

						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}

		return postList;
	}

	// 读取某帖子的信息
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void readPost(ForumPost forumPost) {
		try {
			logger.info("read post url:" + forumPost.getUrl());
			Document postDoc = Jsoup.connect(forumPost.getUrl()).timeout(5000).get();
			Date now = new Date();
			if (forumPost.getId() == null) {
				List<String> imageUrlList = this.readImageList(postDoc, forumPost);
				this.readAttarch(postDoc, forumPost);
				forumPost.setTorrentDownload(0);
				forumPost.setValid(1);
				forumPost.setCreateTime(now);
				forumPostDao.insert(forumPost);

				for (String imageUrl : imageUrlList) {
					ForumPostImage forumPostImage = new ForumPostImage();
					forumPostImage.setPostId(forumPost.getId());
					forumPostImage.setHasDownload(0);
					forumPostImage.setUrl(imageUrl);
					forumPostImage.setCreateTime(now);
					forumPostImageDao.insert(forumPostImage);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	// 读取帖子上的附件信息
	@Override
	public void readAttarch(ForumPost forumPost) {
		try {
			Document postDoc = Jsoup.connect(forumPost.getUrl()).timeout(5000).get();
			this.readAttarch(postDoc, forumPost);
		} catch (SocketTimeoutException se) {
			forumPost.setTorrentName("Read timed out");
		} catch (Exception e) {
			logger.error("", e);
			forumPost.setTorrentName("torrent link not found");
		}
	}

	// 读取某帖子的图片
	@Override
	public List<String> readImageList(ForumPost forumPost) {
		try {
			Document postDoc = Jsoup.connect(forumPost.getUrl()).timeout(5000).get();
			return this.readImageList(postDoc, forumPost);
		} catch (Exception e) {
			logger.error("", e);
		}
		return Lists.newArrayList();
	}

	private List<String> readImageList(Document doc, ForumPost forumPost) {
		List<String> imageUrlList = Lists.newArrayList();
		try {
			String content = "";
			Elements divs = doc.select(".blockcode");
			if (divs.size() == 2) {
				Element divContent = divs.get(1);
				Elements lis = divContent.select("li");
				if (CollectionUtils.isNotEmpty(lis)) {
					for (Element li : lis) {
						String text = li.text();
						if (StringUtils.isNotBlank(text)) {
							if (text.startsWith("[img]")) {
								text = text.replace("[img]", "");
								text = text.replace("[/img]", "");
								imageUrlList.add(text);
							} else if (text.startsWith("http://img")) {
								imageUrlList.add(text);
							} else {
								text = text.replaceAll("\\[color=\\w*\\]", "");
								text = text.replaceAll("\\[size=\\w*\\]", "");
								text = text.replace("[b]", "");
								text = text.replace("[/b]", "");
								text = text.replace("[/color]", "");
								text = text.replace("[/size]", "");
								text = text.replace("[url=", "");
								text = text.replace("[/url]", "");
								content += text + "\r\n";
							}
						}
					}
					// System.out.println("=============content: " + content);
					forumPost.setContent(content);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		// System.out.println("=============imgList: " + imageUrlList);
		return imageUrlList;
	}

	// 读取帖子上的附件信息
	private void readAttarch(Document doc, ForumPost forumPost) {
		try {
			Elements torrentLink = doc.select("ignore_js_op>span>a");
			String torrentUrl = "";
			if (torrentLink.size() > 0) {
				torrentUrl = torrentLink.attr("abs:href");
			} else {
				torrentLink = doc.select("ignore_js_op").select("a");
				// forumPost.setTorrentName(torrentLink.text());
				Elements script = doc.select("ignore_js_op").select("script");
				torrentUrl = torrentLink.attr("abs:href").replace(torrentLink.attr("href"), "") + script.html().substring(script.html().indexOf("href=\"") + "href=\"".length(), script.html().indexOf("\";"));
			}
			if (StringUtils.isNotBlank(torrentUrl)) {
				Thread.sleep(1000);
				Document torrentDoc = Jsoup.connect(torrentUrl).timeout(5000).get();
				String torrentName = torrentDoc.select(".dxksst>div>p>font").text();
				Elements torrentLinkReal = torrentDoc.select(".dxksst>div>p>a");
				String torrentUrlReal = torrentLinkReal.attr("abs:href");
				// System.out.println("=============torrentName: " + torrentName);
				// System.out.println("=============torrentUrlReal: " + torrentUrlReal);
				if (StringUtils.isNotBlank(torrentName)) {
					forumPost.setTorrentName(torrentName);
				} else {
					forumPost.setTorrentName("torrent link not found");
				}
				if (StringUtils.isNotBlank(torrentUrlReal)) {
					forumPost.setTorrentUrl(torrentUrlReal);
				} else {
					forumPost.setTorrentName("torrent link not found");
				}
			} else {
				forumPost.setTorrentName("torrent link not found");
			}
		} catch (SocketTimeoutException se) {
			forumPost.setTorrentName("Read timed out");
		} catch (Exception e) {
			logger.error("", e);
			forumPost.setTorrentName("torrent link not found");
		}
	}

}
